<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Baidu Map Demo</title> 

<link rel="stylesheet" href="css/index.css" type="text/css" />
<link rel="stylesheet" href="css/searchPanel.css" type="text/css" />
<script type="text/javascript"
	src="http://api.map.baidu.com/api?v=2.0&ak=S1gXWo90cg27dQMgmZCMs2Qk5w8opWbv"></script>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>

</head>

<body>
<!--头部开始-->

<style type="text/css">
#l-map {
	height: 100%;
	width: 100%;
}

#r-result {
	width: 100%;
}
</style>

<title>Baidu Map Demo</title>
</head>
<body>
	<div id="left-panel" class="" style="height: 403px;">
		<div id="searchbox" class="clearfix">
			<div id="searchbox-container">
				<div id="sole-searchbox-content" class="searchbox-content">
					<input id="sole-input" class="searchbox-content-common" type="text"
						name="word" autocomplete="off" maxlength="256" placeholder="搜地点"
						value="" />
					<div class="input-clear" title="清空" style="display: none;"></div>
				</div>
			</div>
			<button id="search-button" data-title="搜索" data-tooltip="1"></button>
		</div>
		<ul id="cards-level1" style="pointer-events: auto;" class="cardlist"></ul>
	</div>
	<div id="l-map"></div>
	<div id="results"></div>
	<div id="searchResultPanel"
		style="border: 1px solid red; width: 230px; height: auto; display: none;"></div>

<script type="text/javascript">
	// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	};

	var map = new BMap.Map("l-map", {
		enableMapClick : false
	});

	var size = new BMap.Size(368, 27);
	map.addControl(new BMap.CityListControl({
		anchor : BMAP_ANCHOR_TOP_LEFT,
		offset : size,
	// 切换城市之间事件
	// onChangeBefore: function(){
	//    alert('before');
	// },
	// 切换城市之后事件
	 //onChangeAfter:function(){
	//   alert('after');
	// }
	}));

	//设置默认城市为北京，自动定位到当前城市
	var point = new BMap.Point(116.331398,39.897445);
	map.centerAndZoom(point,12);

	function Fun(result){
		var cityName = result.name;
		map.setCenter(cityName);
		//alert("当前定位城市:"+cityName);
	}
	var myCity = new BMap.LocalCity();
	myCity.get(Fun);


	map.enableScrollWheelZoom(true);//设置缩放

	var ac = new BMap.Autocomplete( //建立一个自动完成的对象
	{
		"input" : "sole-input",
		"location" : map
	});

	ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
		var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province + _value.city + _value.district
					+ _value.street + _value.business;
		}
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = "
				+ value;

		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province + _value.city + _value.district
					+ _value.street + _value.business;
		}
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = "
				+ value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件

		var _value = e.item.value;
		myValue = _value.province + _value.city + _value.district
				+ _value.street + _value.business;
		G("searchResultPanel").innerHTML = "onconfirm<br />index = "
				+ e.item.index + "<br />myValue = " + myValue;

		setPlace();
	});

	var list = "";//获取查询结果集

	var numPage = 0;//记录分页总数

	//给marker添加自定义消息框
	function addClickHandler(content, marker, opt) {
		marker.addEventListener("click", function(e) {
			openInfo(content, e, this, opt);
		});
	};
	//open信息窗口事件
	function openInfo(content, e, obj, opt) {
		//查找当前选中的marker对应的结果面板的li
		for (var i = 0; i < list.length; i++) {
			if (obj == list[i].marker) {
				$("ol li:eq(" + i + ")").find("div:first").click();
			}
		}

		//var p = e.target;
		//var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
		var infoWindow = new BMap.InfoWindow(content, opt); // 创建信息窗口对象 
		obj.openInfoWindow(infoWindow); //开启信息窗口
	};
	

	/**
	选择点的事件  返回地名 地址 lng lat
	 */
	function checkedPoint(title, address, lng, lat) {
		
		var _json={
			"titel":title,
			"address":address,
			"lng":lng,
			"lat":lat
		};
       
         alert(JSON.stringify(_json));
		//console.log(title + "==" + address + "==" + lng + "==" + lat);
	};

	

	function openPanel(index) {
		var opts = {
			width : 230, // 信息窗口宽度
			//height : 80, // 信息窗口高度
			title : "信息窗口", // 信息窗口标题
			enableMessage : true
		//设置允许信息窗发送短息
		};

		var marker = list[index].marker;

		opts.title = '<p style="width:210px;font:bold 14px/16px arial,sans-serif;margin:0;color:#cc5522;white-space:nowrap;overflow:hidden" title="'+list[index].title+'">'
				+ list[index].title
				+ "<a target=\"_blank\" href=\"javascript:void(0)\" onclick=\"checkedPoint('"
				+ list[index].title
				+ "','"
				+ list[index].address
				+ "','"
				+ list[index].point.lng
				+ "','"
				+ list[index].point.lat
				+ "')\" style=\"margin-left:5px;font-size:12px;color:#3d6dcc;font-weight:normal;text-decoration:none;\">选择&raquo;</a></p>";

		var content = '<div style="font:12px arial,sans-serif;margin-top:10px">';
		content += '<table cellspacing="0" style="overflow:hidden;table-layout:fixed;width:100%;font:12px arial,sans-serif">';
		content += '<tbody>';
		content += '<tr>';
		content += '<td style="vertical-align:top;width:38px;white-space:nowrap;word-break:keep-all">地址：&nbsp;</td>';
		content += '<td style="line-height:16px">' + list[index].address
				+ '&nbsp;</td>';
		content += '</tr>';
		content += '</tbody>';
		content += '</table>';
		content += '</div>';
	
		map.centerAndZoom(marker.point, 12);
		var infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象 
		marker.openInfoWindow(infoWindow); //开启信息窗口

	};

	function myFun(results) {
		//map.clearOverlays(); //清除地图上所有覆盖物

		local
				.setMarkersSetCallback(function(pois) {
					
					list = pois;
					for (var i = 0; i < pois.length; i++) {
						var opts = {
							width : 230, // 信息窗口宽度
							//height : 80, // 信息窗口高度
							title : "信息窗口", // 信息窗口标题
							enableMessage : true
						//设置允许信息窗发送短息
						};

						var marker = pois[i].marker;
						
						opts.title = '<p style="width:210px;font:bold 14px/16px arial,sans-serif;margin:0;color:#cc5522;white-space:nowrap;overflow:hidden" title="'+pois[i].title+'">'
								+ pois[i].title
								+ "<a target=\"_blank\" href=\"javascript:void(0)\" onclick=\"checkedPoint('"
								+ pois[i].title
								+ "','"
								+ pois[i].address
								+ "','"
								+ pois[i].point.lng
								+ "','"
								+ pois[i].point.lat
								+ "')\" style=\"margin-left:5px;font-size:12px;color:#3d6dcc;font-weight:normal;text-decoration:none;\">选择&raquo;</a></p>";

						var content = '<div style="font:12px arial,sans-serif;margin-top:10px">';
						content += '<table cellspacing="0" style="overflow:hidden;table-layout:fixed;width:100%;font:12px arial,sans-serif">';
						content += '<tbody>';
						content += '<tr>';
						content += '<td style="vertical-align:top;width:38px;white-space:nowrap;word-break:keep-all">地址：&nbsp;</td>';
						content += '<td style="line-height:16px">'
								+ pois[i].address + '&nbsp;</td>';
						content += '</tr>';
						content += '</tbody>';
						content += '</table>';
						content += '</div>';
						
						addClickHandler(content, marker, opts);
					}

					openPanel(0);
					$("ol li:first").find("div").click();

				});

		switch (local.getStatus()) {
		case BMAP_STATUS_SUCCESS: //数据返回成功  0
		{
			//自定义列表显示  
			toList();
			break;
		}
		case BMAP_STATUS_UNKNOWN_LOCATION: //数据无返回  
		{
			console.log("没数据");
			//var point = results.getPoi(0).point; //获取第一个点，并设置为中心  
			//map.centerAndZoom(point, 17);
			break;
		}
		default: {
			break;
		}
		}
		;

		function toList() {
			var html = "";
			$("#cards-level1").html("");
			html += '<div style="font-style: normal; font-variant: normal; font-weight: normal; font-stretch: normal; font-size: 12px; line-height: normal; font-family: arial, sans-serif; border: 0px solid rgb(153, 153, 153);">';
			html += '<div style="background: rgb(255, 255, 255);height: auto;overflow-y: auto;max-height: 280px;">';
			html += '<ol style="list-style: none; padding: 0px; margin: 0px;">';
			var length = results.getCurrentNumPois();

			
			var pageCount = results.getPageIndex(); //获取结果页数
		
			for (var i = 0, len = results.getCurrentNumPois(); i < len; i++) {
				var poi = results.getPoi(i); //获取每一个智能搜索的结果
				var img = -i * 25;
				img += "px";
				html += "<li style=\"margin: 2px 0px; padding: 0px 4px 0px 0px; cursor: pointer; overflow: hidden; line-height: 17px;\" >";
				html += '<span style="background:url(http://api.map.baidu.com/images/markers.png) -23px '
						+ img
						+ ' no-repeat;width:19px;height:25px;cursor:pointer;float:left;*zoom:1;overflow:hidden;margin:2px 3px 0 5px;*margin-right:0px;display:inline;">&nbsp;</span>';
				html += "<div style=\"zoom: 1; overflow: hidden; padding: 0px 5px;\" onclick=\"openPanel('"
						+ i + "')\">";
				html += '<div style="line-height:20px;font-size:12px;"><span style="color:#7777cc;"><b>'
						+ poi.title + '</b></span></div>';
				html += '<div style="padding:2px 0;line-height:18px;*zoom:1;overflow:hidden;"><b style="float:left;font-weight:bold;*zoom:1;overflow:hidden;padding-right:5px;*margin-right:-3px;">地址:</b>';
				html += '<span style="color:#666;display:block;zoom:1;overflow:hidden;">'
						+ poi.address + '</span></div></div></li>';
			}
			html += '</ol></div>';

			html += '<div style="white-space: nowrap; text-align: right; background: rgb(229, 236, 249); margin-top: 5px; padding: 2px; overflow: hidden; zoom: 1;">';
			
			html += '<div style=" margin-right: 5px;">';
// 分页开始
//上一页 
	html += '<p style="margin:0;padding:0;white-space:nowrap">';
			if (pageCount == 0) {
				html += '<span style="margin-right:3px">上一页</span>';
			} else {
				html += "<span><a style=\"color:#7777cc\" href=\"javascript:void(0)\" onclick=\"ListtoPage("
						+ (pageCount - 1) + ");\">上一页</a></span>";
			}


/**********************************************
		 我们需要计算页码列表的开始和结束位置，即两个变量begin和end
			计算它们需要通过当前页码！
			1. 总页数不足6页--> begin=1, end=最大页
			2. 通过公式设置begin和end，begin=当前页-1，end=当前页+3
			3. 如果begin<1，那么让begin=1，end=6
			4. 如果end>tp, 让begin=tp-5, end=tp
	 */

			 
	var begin = 0, end = 0;
			numPage = results.getNumPages();
			

			if (results.getNumPages() <= 5) {
				begin = 0;
				end = results.getNumPages();
			} else {
				begin = pageCount - 2;
				end = pageCount + 3;
				if (begin < 0) {
					begin = 0;
					end = 5;
				}
				if (end > results.getNumPages()) {
					begin = results.getNumPages() - 5;
					end = results.getNumPages();
				}

			}


	/**********************************************
		 计算begin和end
		 如果总页数<=6，那么显示所有页码，即begin=1 end=${pb.tp}
		 设置begin=当前页码-2，end=当前页码+3
		 如果begin<1，那么让begin=1 end=6
		 如果end>最大页，那么begin=最大页-5 end=最大页
	 */

	for (; begin < end; begin++) {

				if (pageCount == begin) {
					html += "<span style=\"margin-right:3px\">" + (begin + 1)
							+ "</span>";
				} else {
					html += "<span style=\"margin-right:3px\"><a style='color:#7777cc;margin-right:3px' href='javascript:void(0)' onclick=\"ListtoPage("
							+ begin + ");\">" + (begin + 1) + "</a></span>";
				}
			}
// 显示点点点...
	if (end < results.getNumPages()) {
				html += "<span style=\"margin-right:3px\">...</span>";
			}
//下一页 
	if (pageCount == results.getNumPages() - 1) {
				html += "<span style=\"margin-right:3px\">下一页</span>";
			} else {
				html += "<span style=\"margin-right:3px\"><a style=\"color:#7777cc\" href=\"javascript:void(0)\" onclick=\"ListtoPage("
						+ (pageCount + 1) + ");\">下一页</a></span>";
			}
/*
 *共N页 到M页 
 */
	html += "<span style=\"margin-right:3px\">共"
					+ results.getNumPages() + "页</span>";
			html += "<span style=\"margin-right:3px\">到</span>";
			html += '<input type="text"  id="pageCode" style="width:20px;margin-right:3px;" value="'
					+ (pageCount + 1) + '"/>';
			html += "<span style=\"margin-right:3px\">页</span>";
			html += "<a style=\"color:#7777cc\"  onclick=\"javascrip:_go();\">确定</a>";
			html += "</p>";
			<!-- - 分页结束-->
			html += '</div></div></div>';
			$("#cards-level1").html(html);
		}
		;

		var initDiv = function() {
			$("ol li ").each(function() {
				$(this).find("div:first").css("background", "#FFFFFF");
				$(this).find("div:first").mouseover(function() {
					$(this).css("background", "#F6F6F6");
				}).mouseout(function() {
					$(this).css("background", "#FFFFFF");
				});
			});
		};

		initDiv();

		$("ol li ").each(function() {
			$(this).find("div:first").click(function() {
				initDiv();
				//当前被点击的div改变背景色
				$(this).css("background", "#F6F6F6");
				//取消当前div的mouseout和mouseover事件
				$(this).unbind("mouseout");
				$(this).unbind("mouseover");



     var li_height = $(this).parents("li").position().top,//获取当前选中div的li元素的距离ol的高，不包括margin
        div_height = $(this).parents("div").scrollTop();//获取div的滚动条高度
      
				li_height+=div_height;
				if(li_height>280)li_height=300;
				$(this).parents("div").animate({
								scrollTop : li_height
				}, 800);

			});
		});

	};

	function setPlace() {
		map.clearOverlays(); //清除地图上所有覆盖物
		local.search(myValue);
	};

	var local = new BMap.LocalSearch(map, {
		renderOptions : {
			map : map,
			//panel: "cards-level1",//结果容器id  
			autoViewport : true,
			selectFirstResult : false
		},
		//pageCapacity : 10,
		onSearchComplete : myFun
	});

	/**
	 * 给search添加点击事件
	 */
	$("#search-button").bind("click", function() {
		local.search($("#sole-input").val());
	});

	
	//回车查询事件
	$('#sole-input').keydown(function(e) {
		if (e.keyCode == 13) {
			local.search($("#sole-input").val());//处理事件
		}
	});
	
	/**
	分页
	 */
	function _go() {
		var pc = $("#pageCode").val();//获取文本框中的当前页码
		console.log("pc==" + pc);
		if (!/^[1-9]\d*$/.test(pc)) {//对当前页码进行整数校验
			alert('请输入正确的页码！');
			return;
		}
		if (pc > numPage) {//判断当前页码是否大于最大页
			alert('请输入正确的页码！');
			return;
		}
		local.gotoPage(parseInt(pc - 1)); //切换指定页  
	};

	function ListtoPage(index) {
		
		map.clearOverlays(); //清除标点  
		local.gotoPage(index); //切换指定页  
	}

	/**
	 * 给close添加点击事件
	 */
	$(".input-clear").on("click", function() {
		$("#sole-input").val("");
		map.clearOverlays(); //清除地图上所有覆盖物
		map.centerAndZoom("北京", 12); // 初始化地图,设置城市和地图级别。
		$("#cards-level1").html("");
		$(this).hide();
	});

	/**********************************************
	 @function	IE6-9 placeholder与textarea的maxlength修复，并提供值改变时的回调函数供实时捕捉用户输入
	 fixed oncontextmenu delete or cut and backspace
	 @param		id: 必选参数，元素的id
	 @param		fn: 可选参数，实时响应的回调函数
	 @return		通过id获取的元素
	 @note		原理说明：IE6-9动态生成另一个一样的背景透明的输入框叠加到本输入框下层，通过selectionchange、onpropertychange事件与keyup等事件实现实时捕捉，现代谷歌火狐内核的浏览器直接支持placeholder与maxlength，这里用input事件实现了实时输入捕捉；
	 注意点：布局时应在要应用的表单元素父节点上进行相对定位
	 @inadequate	不足：影响了页面结构，未实现事件代理，动态元素必须先插入文档之后再执行此函数实现动态添加的元素placeholder与maxlength修复；IE6-9 onpropertychange也能捕捉到js设置输入框值改变的事件，但现代谷歌火狐内核的浏览器捕捉不到
	 */
	function iChange(id, fn) {
		//var obj = id.nodeType == 1 ? id : id.jQuery ? id[0] : document.getElementById(id),
		var obj = id.nodeType == 1 ? id : document.getElementById(id);
		var doc = obj.document || obj.ownerDocument || document, win = doc.defaultView
				|| doc.parentWindow || window, inputClone = doc
				.createElement(obj.nodeName == 'INPUT' ? 'INPUT' : 'TEXTAREA'), advancedBrowser = 'placeholder' in inputClone, oldValAttr = 'oldvalue'
				+ (+new Date());
		if (advancedBrowser) {
			obj.addEventListener("input", function(e) {
				fn && fn.call(this, e);
			}, false);
		} else {
			//IE6-9
			var docElem = doc.documentElement, inpCloneStyle = inputClone.style, placeholder = obj
					.getAttributeNode('placeholder'), curstyle = obj.currentStyle, objstyle = obj.style;
			placeholder = placeholder ? placeholder.nodeValue : '';
			if (placeholder) {
				//初始化inputClone
				inpCloneStyle.cssText = objstyle.cssText
						+ ';position:absolute;color:graytext;background-color:transparent;border-top-color:transparent;border-right-color:transparent;border-bottom-color:transparent;border-left-color:transparent;';
				inputClone.className = obj.className;
				inputClone.disabled = true;
				if (obj.value === '' || obj.defaultValue === '') {
					inputClone.value = placeholder;
				}

				if (curstyle.position == 'static') {
					objstyle.position = 'relative';
				} else {
					if (typeof curstyle.zIndex == 'number'
							&& curstyle.zIndex > 0) {
						inpCloneStyle.zIndex = --curstyle.zIndex;
					} else {
						inpCloneStyle.zIndex = 0;
					}
				}
				inpCloneStyle.left = obj.offsetLeft + 'px';
				inpCloneStyle.top = obj.offsetTop + 'px';
				obj[oldValAttr] = obj.value;
			}
			var IEwatchChange = function(e) {
				var e = win.event || e, maxLen = obj
						.getAttributeNode('maxlength'), maxLen = maxLen
						&& parseInt(maxLen.nodeValue);

				if (e.type == 'selectionchange' || e.propertyName == "value") {
					var objVal = obj.value;
					if (obj[oldValAttr] !== objVal) {
						if (placeholder) {
							if (objVal === '')
								inputClone.value = placeholder;
							else
								inputClone.value = '';
						}
						//input的maxlength所有浏览器都支持，只有TEXTAREA不支持
						if (maxLen && obj.nodeName == 'TEXTAREA'
								&& objVal.length > maxLen) {
							obj.value = objVal.substring(0, maxLen);
						}
						obj[oldValAttr] = obj.value;
						//两次直接改值会造成光标到开头位置的bug，方法一：延迟后调用回调；方法二：回调中使用正则匹配一遍后再执行赋值
						fn && fn.call(obj, e);
						/*setTimeout(function(){
							fn && fn.call(obj, e);
						}, 0);*/
					}
				}
			};
			if (!win.XMLHttpRequest) {
				//IE6无法聚焦修复
				obj.attachEvent('onclick', function() {
					obj.focus();
				});
				inputClone.attachEvent('onclick', function() {
					obj.focus();
				});
			}
			//现代型事件绑定
			obj.attachEvent("onfocus", function() {
				//主要解决IE9中oncontextmenu delete or cut and backspace事件在onpropertychange时不响应
				document.attachEvent("onselectionchange", IEwatchChange);
			});

			obj.attachEvent("onpropertychange", IEwatchChange);

			obj.attachEvent("onblur", function() {
				document.detachEvent("onselectionchange", IEwatchChange);
			});

			//事件全部绑定后再插入，尽量减少对dom重复渲染
			if (placeholder) {
				objstyle.backgroundColor = 'transparent';
				//IE6,8,9 input在将输入框背景设成透明时无法聚焦bug修复
				objstyle.backgroundImage = 'url(about:blank)';
				obj.parentNode.insertBefore(inputClone, obj);
			}
		}
		return obj;
	}

	//测试用例demo，所有浏览器都兼容
	//实时响应用户输入，然后出现close图标
	iChange(document.getElementById('sole-input'), function(e) {
		var length = parseInt(this.getAttributeNode('maxlength').nodeValue)
				- this.value.length;
		if (length < 256) {
			$(".input-clear").show();
		} else {
			$(".input-clear").hide();
		}
		$("#cards-level1").html("");
		
	});
</script>

<!--主体内容结束-->
</body>
</html>